<template>
  <div class="HomeBox">
    <div ref="target" class="logoImg"></div>
    <div :class="isFixedNav ? 'nav navFixed' : 'nav'">
      <div v-for="(item, key) in menus" :key="key" class="menuItem">
        <span class="menuLabel">{{ item.label }}</span>
      </div>
    </div>
    <div v-if="isFixedNav" style="width: 100%; height: 4rem"></div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      menus: [
        {
          label: "首页",
          router: "/",
        },
        {
          label: "详情",
          router: "/",
        },
        {
          label: "设计师",
          router: "/",
        },
        {
          label: "联系我们",
          router: "/",
        },
      ],
      //节流定时器
      timerScroll: null,
      //是否固定导航
      isFixedNav: false,
    };
  },
  mounted() {
    // this.throttledScroll = this.throttle(() => this.handleScroll(), 100);
    window.addEventListener("scroll", this.handleScroll);
  },
  destroyed() {
    window.removeEventListener("scroll", this.handleScroll);
  },
  methods: {
    /**
     * 监听滚动
     */
    handleScroll() {
      const rect = this.$refs.target.getBoundingClientRect();
      if (Math.abs(rect.y) >= rect.height) {
        this.isFixedNav = true;
      } else {
        this.isFixedNav = false;
      }
    },
    /**
     * 节流
     * @param func
     * @param delay
     */
    throttle(func, delay) {
      let lastTime = 0;
      return function (...args) {
        const now = Date.now();
        if (now - lastTime >= delay) {
          lastTime = now;
          return func.apply(this, args);
        }
      };
    },
  },
};
</script>

<style scoped>
.HomeBox {
  display: flex;
  flex-direction: column;
}
.logoImg {
  width: 100%;
  height: 8rem;
  background: #f0f0f0;
}
.nav {
  justify-content: space-around;
  align-items: center;
  box-sizing: border-box;
  display: flex;
  background: white;
  border-bottom: 1px solid #f0f0f0;
  height: 4rem;
  width: 100%;
}
.navFixed {
  position: fixed;
  top: 0rem;
  z-index: 10;
}
.menuItem {
  padding: 1rem;
  box-sizing: border-box;
  display: flex;
  justify-content: center;
  align-items: center;
  /* font-family: "ZHCJKT"; */
}
.menuItem span {
  background: linear-gradient(to right, #000, #000) no-repeat right bottom;
  background-size: 0 2px;
  transition: background-size 100ms;
}
.menuItem span:hover {
  background-position-x: left;
  background-size: 100% 2px;
}
.menuLabel {
  cursor: pointer;
  padding-bottom: 0.5rem;
  box-sizing: border-box;
}
</style>
